import { loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
//使用svg需要的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//mock
import { UserConfigExport, ConfigEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  //获取各种环境下的对应的变量
  //process.cwd() 获取根目录
  let env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vue(),
      createSvgIconsPlugin({
        //Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        //Specify symbol fromat
        symbolId: 'icon-[dir]-[name]',
      }),
      viteMockServe({
        localEnabled: command === 'serve', //保证开发阶段可以使用mock接口
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve('./src'), //相对路径别名配置，使用@ 代替src
      },
    },
    //scss全局变量
    css: {
      preprocessorOptions: {
        scss: {
          //引入全局变量
          additionalData: '@use "@/styles/variable.scss" as *;',
        },
      },
    },
    // 配置代理，解决跨域问题
    server: {
      proxy: {
        [env.VITE_API_BASE_API]: {
          //获取数据的服务器地址
          target: env.VITE_SERVE,
          //是否开启跨域
          changeOrigin: true,
          //重写路径,将/api 替换为空
          //new RegExp('^' + env.VITE_API_BASE_URL), ''
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
  }
}
